#include <iostream>
#include <cstdlib>

#include "lib/dlm.h"
#include "lib/DLM_Coordinator.h"

using namespace std;

int main(int argc, char** argv)
{
	DLM_Coordinator koordynator;
	cout << "Running main program" << endl;

	int result = DLM_init(5);
	if(result == DLM_INIT_FAIL_STATUS)
	{
		cerr << "Error in DLM init" << endl;
	}
	else if(result == DLM_INIT_OK_CLIENT_STATUS)
	{
		char flag;
		int resource_id, lock_type;
		long timeout;
		int result;

		while(read_msg(&flag, &resource_id, &lock_type, &timeout) == DLM_RETURN_OK)
		{
			switch(flag) {
			case MSG_FLAG_LOCK:
				cout << "Client " << getpid() << " locking resource " << resource_id << endl;
				result = DLM_lock(resource_id, lock_type, timeout);
				cout << "Client " << getpid() << " lock "
					<< (result == DLM_RETURN_FAIL ? "timeout" : "obtained") << endl;
				break;
			case MSG_FLAG_UNLOCK:
				cout << "Client " << getpid() << " unlocking resource " << resource_id << endl;
				DLM_unlock(resource_id);
				cout << "Unlock finished" << endl;
				break;
			case MSG_FLAG_TRYLOCK:
				cout << "Client " << getpid() << " trying to obtain lock " << resource_id << endl;
				result = DLM_trylock(resource_id, lock_type);
				cout << "Client " << getpid() << " trylock " << resource_id << " result:"
					<< (result == DLM_RETURN_OK ? "free" : "used") << endl;
				break;
			case MSG_FLAG_QUIT:
				cout << "Client process " << getpid() << " end" << endl;
				DLM_cleanup();
				return 0;
			}
		}

	}
	else
	{
		string value;
		cout << "Coordinator: " << getpid() << endl;
		koordynator.run(cout);
		cout << "Closing coordinator" << endl;
	}

	DLM_cleanup();

	return 0;
}
